# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Group, Permission, GroupPermission, BMSUser, UserGroup


class ListController(BaseController):

    def get(self):
        g = Group.objects
        group_name = self.get_argument('roleName', '')
        if group_name:
            g = g.filter(name__contains=group_name)
        disabled = self.int_argument('disabled', 0)
        g = g.filter(disabled=disabled).order_by('show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(g.all(), number_per_page=number_per_page, m2m_fields=['permissions'])
        return self.render_json(data=paginator)


class DetailController(BaseController):

    def get(self):
        group_id = self.int_argument('id', 0)
        if group_id <= 0:
            return self.render_json(code=1001, msg='参数错误')

        g = Group.objects.filter(id=group_id).first()
        if not g:
            return self.render_json(code=1001, msg='指定ID的分组不存在')            

        return self.render_json(data=g.to_dict())


class ListAllGroupsController(BaseController):

    def get(self):
        groups = Group.objects.filter(disabled=0).order_by('show_order').all()
        data = [ {'label': g.name, 'value': g.id} for g in groups]
        return self.render_json(data={'group_options': data})


class BaseGroupController(BaseController):

    def save_group(self, group, data):
        group.name = data.get('name')
        group.description = data.get('description')
        group.disabled = data.get('disabled')
        group.show_order = data.get('show_order')
        group.save()
        return group


class CreateGroupController(BaseGroupController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='分组名称不能为空')

        group = Group()
        group = self.save_group(group, data)
        return self.render_json(data=group.to_dict())


class UpdateGroupController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='分组名称不能为空')
        group_id = data['id']

        group = group.objects.filter(id=group_id).first()
        group = self.save_group(group, data)
        return self.render_json(data=group.to_dict())


class CreateGroupPermissioinController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['permissionIds']:
            return self.render_json(code=1001, msg='至少选择一个权限')
        group_id = data['groupId']
        if int(group_id) <= 0:
            return self.render_json(code=1001, msg='组ID错误')

        group = Group.objects.filter(id=group_id).first()
        if not group:
            return self.render_json(code=1001, msg='没有找到指定ID的分组数据')

        # 删除所有原来的权限
        GroupPermission.objects.filter(group_id=group_id).all().delete()
        permission_list = Permission.objects.filter(id__in=data['permissionIds']).all()
        for r in permission_list:
            group_permission = GroupPermission()
            group_permission.group = group
            group_permission.permission = r
            group_permission.save()
        return self.render_json()


class DeleteGroupController(BaseController):

    def post(self, group_id):
        group_id = int(group_id)
        if group_id > 0:
            group = Group.objects.filter(id=group_id).first()
            if group:
                group.delete()

        return self.render_json()


class PermissionListController(BaseController):

    def get(self):
        p = Permission.objects
        permission_name = self.get_argument('permissionName', '')
        if permission_name:
            p = p.filter(name__contains=permission_name)

        disabled = self.int_argument('disabled', 0)
        p = p.filter(disabled=disabled).filter(parent_id__isnull=True).order_by('show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination_contain_objects_no_records(p.all(), number_per_page=number_per_page)
        records = []
        for c in paginator['objects']:
            records = records + c.cate_level_1_to_dict()
        paginator['records'] = records
        paginator.pop('objects')

        return self.render_json(data=paginator)


class PermissionMunuItemsController(BaseController):

    def get(self):
        menu_items = Permission.objects.filter(cate=0).filter(disabled=0).order_by('created_at').all()
        data = [{'value': p.id, 'label': p.name} for p in menu_items]

        return self.render_json(data={'menuItems': data})


class PermissionDetailController(BaseController):

    def get(self):
        permission_id = self.int_argument('id', 0)
        if permission_id <= 0:
            return self.render_json(code=1001, msg='参数错误')

        permission = Permission.objects.filter(id=permission_id).first()
        if not permission:
            return self.render_json(code=1001, msg='指定ID的权限不存在')            

        return self.render_json(data=permission.to_dict())


class PermissionOptionsListController(BaseController):

    def get(self):
        permission_in_db = Permission.objects.filter(disabled=0).order_by('parent_id').order_by('show_order').all()
        data = [ p.to_option_dict() for p in permission_in_db ]
        return self.render_json(data=data)


class GroupPermissionsController(BaseController):

    def get(self):
        id = self.int_argument('id', 0)
        if id <= 0:
            return self.render_json(code=1001, msg='参数错误')
        group = Group.objects.filter(id=id).first()
        data = [ p.id for p in group.permissions.all() ]
        return self.render_json(data={'permissions':data})


class PermissionTreeController(BaseController):

    def get(self):
        top_permission_in_db = Permission.objects.filter(disabled=0).filter(parent_id__isnull=True).order_by('show_order').all()
        rslt = []
        for l1 in top_permission_in_db:
            d1 = l1.to_tree_dict()
            rslt.append(d1)
            for l2 in l1.sub_cates:
                d2 = l2.to_tree_dict()
                d1['children'].append(d2)
                for l3 in l2.sub_cates:
                    d3 = l3.to_tree_dict()
                    del d3['children']
                    d2['children'].append(d3)
        return self.render_json(data={'tree_data':rslt})


class PermissionBaseController(BaseController):
    
    def save_permission(self, permission, data):
        parent_id = data.get('parent_id', '0')
        if parent_id and int(parent_id) > 0:
            permission.parent_id = int(parent_id)
        permission.name = data['name']
        permission.description = data['description']
        permission.cate = data['cate']
        permission.permission_code = data['permission_code']
        permission.url = data.get('url', '')
        permission.icon = data.get('icon', '')
        permission.disabled = data['disabled']
        permission.show_order = data['show_order']
        permission.save()
        return permission
        

class CreatePermissionController(PermissionBaseController):

    def post(self):
        data = json.loads(self.request.body)
        print(data)
        if not data['name']:
            return self.render_json(code=1001, msg='资源名称不能为空')

        permission = Permission()
        permission = self.save_permission(permission, data)
        return self.render_json(data=permission.to_dict())


class UpdatePermissionController(PermissionBaseController):

    def post(self):
        data = json.loads(self.request.body)
        print(data)
        if not data['name']:
            return self.render_json(code=1001, msg='资源名称不能为空')
        permission_id = data['id']

        permission = Permission.objects.filter(id=permission_id).first()
        permission = self.save_permission(permission, data)
        return self.render_json(data=permission.to_dict())


class DeletePermissionController(BaseController):

    def post(self, permission_id):
        """菜单删除功能使用软删除方式
        """
        permission_id = int(permission_id)
        if permission_id > 0:
            permission = Permission.objects.filter(id=permission_id).first()
            if permission:
                permission.disabled = 1
                permission.save()
                # permission.delete()

        return self.render_json()


class BMSUserListController(BaseController):

    def get(self):
        bms_user = BMSUser.objects
        user_name = self.get_argument('user_name', '')
        if user_name:
            bms_user = bms_user.filter(first_name__contains=user_name)

        is_active = self.int_argument('is_active', 1)
        bms_user = bms_user.filter(is_active=is_active).order_by('date_joined')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(bms_user.all(), number_per_page=number_per_page)

        return self.render_json(data=paginator)


class BMSUserDetailController(BaseController):

    def get(self):
        bms_user = BMSUser.objects
        id = self.get_argument('id', '')
        if not id:
            return self.render_json(code=1001, msg='参数错误')
        exist_user = BMSUser.objects.filter(id=id).first()
        if not exist_user:
            return self.render_json(code=1001, msg='用户不存在')

        return self.render_json(data=exist_user.to_dict())


class CreateBMSUserController(BaseController):

    def post(self):
        """菜单删除功能使用软删除方式
        """
        data = json.loads(self.request.body)
        username = data.get('username')
        password = data.get('password')
        if not username and not password:
            return self.render_json(code=1001, msg='登录名和密码不能为空')

        exist_user = BMSUser.objects.filter(username=username).first()
        if exist_user:
            return self.render_json(code=1001, msg='用户名已存在！创建失败！')            
        nickname = data.get('nickname', '')
        user = BMSUser.objects.create_user(username=username, password=password, first_name=nickname)
        group_id = data.get('group_id', '')
        if group_id:
            group = Group.objects.filter(id=group_id).first()
            if group:
                ug = UserGroup()
                ug.group = group
                ug.user = user
                ug.save()

        return self.render_json(msg='用户创建成功')


class UpdateBMSUserController(PermissionBaseController):

    def post(self):
        data = json.loads(self.request.body)
        user_id = data['id']

        user = BMSUser.objects.filter(id=user_id).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        nickname = data.get('nickname', '')
        if nickname:
            user.first_name = nickname
            user.save()

        group_id = data.get('group_id', '')
        if group_id:
            group = Group.objects.filter(id=group_id).first()
            UserGroup.objects.filter(user=user).delete()
            ug = UserGroup()
            ug.group = group
            ug.user = user
            ug.save()
        return self.render_json(msg='用户信息修改成功')


class ResetPasswordController(PermissionBaseController):

    def post(self):
        data = json.loads(self.request.body)
        user_id = data['id']

        user = BMSUser.objects.filter(id=user_id).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        user.reset_password()

        return self.render_json(data={'now_password': BMSUser.DEFAULT_PASSWORD})


class DeleteBMSUserController(BaseController):

    def post(self, user_id):
        """菜单删除功能使用软删除方式
        """
        user_id = int(user_id)
        if user_id > 0:
            user = BMSUser.objects.filter(id=user_id).first()
            if user:
                user.is_active = 0
                user.save()

        return self.render_json()
